package cn.hongyu.dao.impl;

import cn.hongyu.dao.UserDao;
import cn.hongyu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public List<User> list() {
        List<User> list = jdbcTemplate.query("select * from sys_user ", new BeanPropertyRowMapper<User>(User.class));
        return list;
    }

    @Override
    public Long save(User user) {
        /*jdbcTemplate.update("insert into sys_user values (?,?,?,?,?)",
                null,user.getUsername(),user.getEmail(),user.getPassword(),user.getPhoneNum());*/
        //创建对象
        PreparedStatementCreator creator = new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                //原生jdbc
                PreparedStatement preparedStatement=connection.prepareStatement("insert into sys_user values (?,?,?,?,?)",
                        PreparedStatement.RETURN_GENERATED_KEYS);
                preparedStatement.setObject(1,null);
                preparedStatement.setString(2,user.getUsername());
                preparedStatement.setString(3,user.getEmail());
                preparedStatement.setString(4, user.getPassword());
                preparedStatement.setString(5,user.getPhoneNum());
                return preparedStatement;
            }
        };
        GeneratedKeyHolder holder = new GeneratedKeyHolder();
        jdbcTemplate.update(creator,holder);
        long id = holder.getKey().longValue();
        return id;//返回当前保存的用户id 该id时数据库自动生成的
    }

    @Override
    public void saveUserRoleRel(Long id, Long[] roleIds) {
        for(Long roleid:roleIds) {
            jdbcTemplate.update("insert into sys_user_role values (?,?)", id, roleid);
        }
    }


}
